package cn.cyh.imeans.utils;

import cn.cyh.imeans.api.R;
import com.xiaoleilu.hutool.collection.CollUtil;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;
import java.util.StringJoiner;

public class Valid {

    private Valid(){}

    /**
     * 参数校验
     * @param isUpdate 是否是更新
     */
    public static R validData(Object zb, boolean isUpdate, Class group){
        Class<?>[] groups = new Class[]{isUpdate ? UpdateGroup.class : AddGroup.class, group};
        R validate = Valid.validate(zb, groups);
        if(!validate.isSuccess()) {
            return validate;
        }

        return R.status(true);
    }

    private static R validate(Object o, Class<?>... groups){
        ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
        Validator validator = validatorFactory.getValidator();
        Set<ConstraintViolation<Object>> set = validator.validate(o, groups);
        if(CollUtil.isEmpty(set)) {
            return R.status(true);
        }
        StringJoiner sj = new StringJoiner(",");
        for (ConstraintViolation<Object> violation : set) {
            sj.add(violation.getMessage());
        }
        return R.fail(sj.toString());
    }

}
